package com.atguigu.tingshu.common.login;

import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.lang.reflect.Method;

/**
 * 验证用户身份注解增强切面类
 *
 * @author: atguigu
 * @create: 2024-02-22 10:14
 */
@Slf4j
@Aspect
@Component
public class LoginAspect {

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 环绕通知逻辑，作用到切入点上（所有使用@GuiguLogin方法）
     *
     * @param pjp 目标方法对象
     * @return 目标方法执行结果
     * @throws Throwable
     */
    @Around("@annotation(guiGuLogin)")
    public Object authAround(ProceedingJoinPoint pjp, GuiGuLogin guiGuLogin) throws Throwable {

        //todo 采用切入点对象获取方法上注解属性值
        //Signature signature = pjp.getSignature();
        //MethodSignature methodSignature = (MethodSignature) signature;
        //Method method = methodSignature.getMethod();
        //GuiGuLogin annotation = method.getAnnotation(GuiGuLogin.class);
        //boolean require = annotation.require();

        //一 前置通知
        log.info("----------前置通知.....");
        //1.获取请求对象HttpServletRquest
        //1.1 从请求上下文中获取RequestAttributes接口-从ThreadLocal<RequestAttributes>中获取到的  思考：什么时候存进去的？？
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        //1.2 将RequestAttributes接口转为实现类ServletRequestAttributes
        ServletRequestAttributes sra = (ServletRequestAttributes) requestAttributes;

        //1.3 获取请求对象
        HttpServletRequest request = sra.getRequest();

        //1.4 获取小程序端token令牌
        String token = request.getHeader("token");

        //2.验证token令牌
        //2.1 拼接用户登录key 形式：user:login:token令牌  登录存入Value：UserInfoVo对象
        String loginKey = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
        UserInfoVo userInfoVo = (UserInfoVo) redisTemplate.opsForValue().get(loginKey);

        //3.token没有查询到对应用户信息 目标方法要求登录方可访问 抛出异常：业务状态码：208,小程序引导用户登录
        if (guiGuLogin.require() && userInfoVo == null) {
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }

        //4.如果用户登录，将用户ID存入ThreadLocal 方便后续controller、service、mapper都可以获取当前登录用户ID
        if (userInfoVo != null) {
            AuthContextHolder.setUserId(userInfoVo.getId());
        }
        Object retVal;
        try {
            //二 执行目标方法（凡是在方法上加@GuiGuLogin注解）
            retVal = pjp.proceed();

        } finally {
            //三 后置通知
            log.info("----------后置通知.....");
            //5.清理ThreadLocal中用户信息-避免内存泄漏
            AuthContextHolder.removeUserId();
        }
        return retVal;
    }

}
